package com.ltxtiyu.video.tool;


import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;

/**
 * 根据字符串获得属性值
 * @author xhh151021
 *
 */
public class ObjectTool {
	
	/**
	 * 根据字符串获得属性值
	 * @param fieldName
	 * @param o
	 * @return
	 */
	public static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			//System.out.println("属性不存在");
			return null;
		}
	}

	public static Integer numberNullConvert(String o){
		Integer result = -1;
		try {
			result = Integer.valueOf(o);
		} catch (Exception e) {
			return -1;
		}
		return result;
	}


	public static BigDecimal numberNullConvert(BigDecimal o){
		return null==o? BigDecimal.ZERO:o;
	}
	
	/**
	 * 转换时间
	 * @param o
	 * @return
	 */
	public static Date dateNullConvert(String o, String format){
		try {
			Calendar c = Calendar.getInstance();
			c.setTimeInMillis(Long.parseLong(o));
			Date date = c.getTime();
			return date;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	public static BigDecimal numberNullConvert(String o, BigDecimal b){
		BigDecimal result = BigDecimal.ZERO;
		try {
			result = new BigDecimal(o);
		} catch (Exception e) {
			return b;
		}
		return result;
	}
	public static Integer numberNullConvert(String o, Integer b){
		Integer result = 0;
		try {
			result = Integer.valueOf(o);
		} catch (Exception e) {
			return b;
		}
		return result;
	}
	public static Integer numberNullConvert(Integer o){
		if(null!=o&&o>0)
			return o;
		else
			return -1;
	}
	
	public static Integer numberNullConvert(Integer o, Integer b){
		if(null!=o)
			return o;
		else
			return b;
	}
	
	public static Double numberNullConvert(String o, Double d){
		Double result = 0.0;
		try {
			result = Double.valueOf(o);
		} catch (Exception e) {
			return d;
		}
		return result;
	}
	
	public static String stringNullConvert(String o){
		return null!=o&&o.length()>0?o:"";
	}

    public static String stringOrNull(String o){
        if(o == null || "".equals(o)){
            return null;
        }
        return o;
    }

    public static Integer numberOrNull(String o){
        Integer result;
        try {
            result = Integer.valueOf(o);
        } catch (Exception e) {
            result = null;
        }
        return result;
    }

	/**返回Map<String,Object>类型的对象*/
	@SuppressWarnings("rawtypes")
	public static Map getMap(String[] setKeys, Object[] setBodys){
		Map<String,Object> map = new HashMap<String, Object>();
		if(setKeys.length>0&&setBodys.length>0){
			for (int i = 0; i< setBodys.length; i++) {
				map.put(setKeys[i], setBodys[i]);
			}
		}
		return map;
	}
}
